﻿namespace NTLib.Core.Serialization
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Threading.Tasks;

    /// <summary>
    /// Serializer in and out of json.
    /// </summary>
    /// <seealso cref="NTLib.Core.Serialization.ISerializor" />
    public class DataContractJsonSerializerSlim : ISerializor
    {
        #region Methods

        /// <summary>
        /// Read an object from a stream.
        /// </summary>
        /// <param name="wantedType"></param>
        /// <param name="stream"></param>
        /// <returns></returns>
        public object ReadObject(Type wantedType, Stream stream)
        {
            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(wantedType);
            return jsonSerializer.ReadObject(stream);
        }

        /// <summary>
        /// Read an object from a stream.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="stream"></param>
        /// <returns></returns>
        public T ReadObject<T>(Stream stream)
        {
            return (T)ReadObject(typeof(T), stream);
        }

        /// <summary>
        /// Writes the object into the stream using a json serializer.
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="stream"></param>
        public void WriteObject(object obj, Stream stream)
        {
            if (object.Equals(obj, null))
                throw new ArgumentNullException(nameof(obj));
            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType());
            jsonSerializer.WriteObject(stream, obj);
        }

        #endregion
    }
}
